//
//  BTELunchViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/5.
//

import UIKit
import SnapKit
import Alamofire

fileprivate let LUNCHED = "LUNCHED"

let PROTOCOL = "PROTOCOL"

class BTELunchViewController: UIViewController {
    
    let reachMa = NetworkReachabilityManager()
    
    fileprivate let server = BTELunchNetServer()
    
    private let bgImage = UIImageView.init(image: UIImage.init(named: "lunch"))

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(bgImage)
        bgImage.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        switch UIDevice.current.types {
        case .iPad2,
                .iPad3,
                .iPad4,
                .iPadAir,
                .iPadAir2,
                .iPadAir3,
                .iPadAir4,
                .iPadAir5,
                .iPad5,
                .iPad6,
                .iPad7,
                .iPad8,
                .iPad9,
                .iPad10,
                .iPadMini,
                .iPadMini2,
                .iPadMini3,
                .iPadMini4,
                .iPadMini5,
                .iPadMini6,
                .iPadPro9_7,
                .iPadPro10_5,
                .iPadPro11,
                .iPadPro2_11,
                .iPadPro3_11,
                .iPadPro12_9,
                .iPadPro2_12_9,
                .iPadPro3_12_9,
                .iPadPro4_12_9,
                .iPadPro5_12_9:
            reachMa?.startListening {[weak self] status in
                switch status {
                case .notReachable:
                    BTEHUD.shared.showError("Network Error", on: (self?.view)!)
                    BTELanguageManager.shared.configure(languageCode: 1)
                    self?.fixmefunction()
                    break
                case .reachable(.ethernetOrWiFi), .reachable(.cellular):
                    BTELanguageManager.shared.configure(languageCode: 1)
                    self?.fixmefunction()
                case .unknown:
                   break
                }
            }
            break
        default:
            reachMa?.startListening {[weak self] status in
                switch status {
                case .notReachable:
//                    BTEHUD.shared.showError("Network Error", on: (self?.view)!)
                    break
                case .reachable(.ethernetOrWiFi), .reachable(.cellular):
                    
                    // stva
                    DispatchQueue.main.asyncAfter(deadline: .now()+3){
                        BTEDeviceIdentifierManager.shared.requestTrackingAuthorizationIfNeeded { response in
                            if response {
                                BTEDeviceIdentifierManager.storeVendorIDIfNeeded()
                                BTEDeviceIdentifierManager.shared.uploadIDVA()
                            }
                        }
                    }
                    
                    // location
                    LocationService.shared.requestLocationInfo { result in
                        switch result {
                        case .success((_, let info)):
                            LocationUploader.upload(info)
                        case .failure(let error):
                            print("获取定位失败: \(error)")
                        }
                    }
                    
                    // deviceinfo
                    DeviceInfoCollector.collectSummary { info in
                        DeviceInfoCollector.uploadInfomation(info)
                    }
                    
                    self?.lunchfunction()
                case .unknown:
                   break
                }
            }
        }
    }
    
}



extension BTELunchViewController {
    
    func lunchfunction(){
        startNet(with: ROOT_PATH) { of in
            if !of {
                self.hostserch { hosts in
                    self.fintrighthost(hosts: hosts)
                }
            }
        }
    }
    
    
    func startNet(with host: String, handle: @escaping (Bool) -> Void){
        let datas = ["jeopardised":DeviceInfo.getPreferredLanguage(),
                     "carneol":"\(NetworkInfo.isVPNEnabled() ? 1 : 0)",
                     "qurshes":"\(NetworkInfo.isUsingProxy() ? 1 : 0)"]
        server.lunch(host: host, data: datas) {[weak self] result in
            switch result {
            case .success(let success):
                
                guard let model = success?.sidelingwise else {
                    return
                }
                
                BTELanguageManager.shared.configure(languageCode: model.unpernicious)
                
                // 加载地址
                BTEAddressManager.stand.loadAddress()
                
                UserDefaults.standard.setValue(model.sacculated!, forKey: PROTOCOL)
                
                if let facemodel = model.subsale {
                    let confi = FacebookConfiguration.init(urlSchemeSuffix: facemodel.subvii!,
                                                           appID: facemodel.undonated!,
                                                           displayName: facemodel.palaeoglaciology!,
                                                           clientToken: facemodel.vasovagal!)
                    FacebookSDKManager.shared.configure(with: confi)
                }
                
                
                self?.fixmefunction()
                
                handle(true)
                
                break
            case .failure(let failure):
                handle(false)
                break
            }
        }
    }
    
    func fixmefunction(){
        if let window  = UIApplication.shared.windows.first {
            let isLunched = UserDefaults.standard.value(forKey: LUNCHED) as? String
            if isLunched == nil {
                let lunchvc = IntroViewController()
                window.rootViewController = lunchvc
                lunchvc.didFinishIntro = {
                    UserDefaults.standard.set("1", forKey: LUNCHED)
                    let roo = BTEBaseTabBarController()
                    
                    let home = BTEHomeViewController()
                    roo.addChild(BTEBaseNavigationViewController.init(rootViewController: home))
                    
                    let ode = BTEOrderViewController()
                    roo.addChild(BTEBaseNavigationViewController.init(rootViewController: ode))
                    
                    let nm = BTEMeViewController()
                    roo.addChild(BTEBaseNavigationViewController.init(rootViewController: nm))
                    
                    roo.selectedIndex = 0
                    
                    window.rootViewController = roo
                }
            } else {
                let roo = BTEBaseTabBarController()
                
                let home = BTEHomeViewController()
                roo.addChild(BTEBaseNavigationViewController.init(rootViewController: home))
                
                let ode = BTEOrderViewController()
                roo.addChild(BTEBaseNavigationViewController.init(rootViewController: ode))
                
                let nm = BTEMeViewController()
                roo.addChild(BTEBaseNavigationViewController.init(rootViewController: nm))
                
                roo.selectedIndex = 0
                
                window.rootViewController = roo
            }
        }
    }

}


extension BTELunchViewController {
    
    func hostserch(handle: @escaping ([hostmodels]) -> Void) {
        server.findhosturl { result in
            switch result {
            case .success(let data):
                handle(data?.sidelingwise ?? [])
            case .failure(let erro):
                break
            }
        }
    }
    
    func fintrighthost(hosts: [hostmodels], idx: Int = 0) {
        guard idx < hosts.count else {
            return
        }
        startNet(with: hosts[idx].stan!) { success in
            if success {
                ROOT_PATH = hosts[idx].stan!
            } else {
                self.fintrighthost(hosts: hosts, idx: idx + 1)
            }
        }
    }
    
    
   
}
